//
//  NSString+Additions.m
//  IOSDuoduo
//
//  Created by xxx on 14-5-23.
//  Copyright (c) 2014年 xxx. All rights reserved.
//

#import "NSString+Additions.h"

#import <sys/xattr.h>

#import <CommonCrypto/CommonDigest.h>
#import <UIKit/UIKit.h>

#define GB18030_ENCODING CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)

@implementation NSString (TTString)

+(NSString *)documentPath {
    static NSString * path = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
                 objectAtIndex:0] copy];
        [NSString addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path]];
    });
    return path;
}
+(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    if (URL==nil) {
        return NO;
    }
    NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
    float version=[systemVersion floatValue];
    if (version<5.0) {
        return YES;
    }
    if ( version>=5.1) {
        assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
        
        NSError *error = nil;
        BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
                                      forKey: NSURLIsExcludedFromBackupKey error: &error];
        if(!success){
        }
        return success;
    }
    
    if ([systemVersion isEqual:@"5.0"]) {
        return NO;
    }else{
        assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
        
        const char* filePath = [[URL path] fileSystemRepresentation];
        
        const char* attrName = "com.apple.MobileBackup";
        u_int8_t attrValue = 1;
        
        int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
        return result == 0;
    }
    return YES;
}

+(NSString *)cachePath {
    static NSString * path = nil;
    if (!path) {
        path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)
                 objectAtIndex:0] copy];
    }
    return path;
}

+(NSString *)formatCurDate {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *result = [dateFormatter stringFromDate:[NSDate date]];
    
    return result;
}

+(NSString *)formatCurDay {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *result = [dateFormatter stringFromDate:[NSDate date]];
    
    return result;
}

+(NSString *)formatCurDayForVersion {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy.MM.dd"];
    NSString *result = [dateFormatter stringFromDate:[NSDate date]];
    
    return result;
}

+ (NSString *)getAppVer {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
}

- (NSURL *) toURL {
    return [NSURL URLWithString:[self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}

- (BOOL)isEmpty {
    return !self || nil == self
    || 0 == [[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length];
}

- (NSString *)MD5 {
    // Create pointer to the string as UTF8
	const char* ptr = [self UTF8String];
	unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
    
	// Create 16 byte MD5 hash value, store in buffer
	CC_MD5(ptr, (CC_LONG)strlen(ptr), md5Buffer);
    
	// Convert MD5 value in the buffer to NSString of hex values
	NSMutableString* output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
	for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
		[output appendFormat:@"%02x", md5Buffer[i]];
	}
    
	return output;
}

- (NSString *)trim {
    return  [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (BOOL)isOlderVersionThan:(NSString*)otherVersion {
	return ([self compare:otherVersion options:NSNumericSearch] == NSOrderedAscending);
}

- (BOOL)isNewerVersionThan:(NSString*)otherVersion {
	return ([self compare:otherVersion options:NSNumericSearch] == NSOrderedDescending);
}

- (NSString*)removeAllSpace {
    NSString* result = [self stringByReplacingOccurrencesOfString:@" " withString:@""];
    result = [result stringByReplacingOccurrencesOfString:@"    " withString:@""];
    return result;
}

#pragma mark - compare

- (NSComparisonResult)ctalkCompare:(NSString *)strToCompare
{
    if ([NSString startsWithChinese:self] && [NSString startsWithChinese:strToCompare]) {
        
        NSLog(@"%@ compare to %@",self, strToCompare);
        
        return [self chineseCompare:strToCompare];
    }
    
    return [self compare:strToCompare];
}

- (NSComparisonResult)chineseCompare:(NSString *)strToCompare
{
    //NSString *str1 = [self stringByAddingPercentEscapesUsingEncoding:GB18030_ENCODING];
    //NSString *str2 = [strToCompare stringByAddingPercentEscapesUsingEncoding:GB18030_ENCODING];
    NSString *str1 = [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *str2 = [strToCompare stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    return [str1 compare:str2];
}

+ (BOOL)startsWithChinese:(NSString *)str
{
    //是否以中文开头(unicode中文编码范围是0x4e00~0x9fa5)
    int utfCode = 0;
    void *buffer = &utfCode;
    NSRange range = NSMakeRange(0, 1);
    //判断是不是中文开头的,buffer->获取字符的字节数据 maxLength->buffer的最大长度 usedLength->实际写入的长度，不需要的话可以传递NULL encoding->字符编码常数，不同编码方式转换后的字节长是不一样的，这里我用了UTF16 Little-Endian，maxLength为2字节，如果使用Unicode，则需要4字节 options->编码转换的选项，有两个值，分别是NSStringEncodingConversionAllowLossy和NSStringEncodingConversionExternalRepresentation range->获取的字符串中的字符范围,这里设置的第一个字符 remainingRange->建议获取的范围，可以传递NULL
    BOOL b = [str getBytes:buffer maxLength:2 usedLength:NULL encoding:NSUTF16LittleEndianStringEncoding options:NSStringEncodingConversionExternalRepresentation range:range remainingRange:NULL];
    if (b && (utfCode >= 0x4e00 && utfCode <= 0x9fa5))
        return YES;
    else
        return NO;
    
}

- (BOOL)isAllSpaceCharacter
{
    for (int i = 0; i<[self length]; i++) {
        //截取字符串中的每一个字符
        NSString *strSub = [self substringWithRange:NSMakeRange(i, 1)];
        if (![strSub isEqualToString:@" "]) {
            return NO;
        }
    }
    return YES;
}


- (NSString *)telNumberFormat
{
    NSMutableString *stringWithAddedSpaces = [NSMutableString new];

    if (11 != self.length) {
        return self;
    }
    
    for (NSUInteger i = 0; i < self.length; ++i) {
        
        // 在第4、8位插入空格
        if ((3 == i) || (7 == i)) {
            
            [stringWithAddedSpaces appendString:@" "];
        }
        
        // 拼接得到插入空格以后的字符串
        unichar characterToAdd = [self characterAtIndex:i];
        NSString *stringToAdd = [NSString stringWithCharacters:&characterToAdd length:1];
        [stringWithAddedSpaces appendString:stringToAdd];
    }
    return [stringWithAddedSpaces copy];
}


/**
 *  指定字符串出现的次数
 *
 *  @param searchString 需要判断的字符串
 *
 *  @return NSUInteger出现的次数
 */
- (NSUInteger)countOccurencesOfString:(NSString*)searchString {
    
    // 获得替换字符串后，减少的字符串长度
    NSInteger strCount = [self length] - [[self stringByReplacingOccurrencesOfString:searchString withString:@""] length];
    
    // 获得被替换掉的字符串次数
    return strCount / [searchString length];
}

/**
 *  截取URL中的参数
 *
 *  @return NSMutableDictionary parameters
 */
- (NSMutableDictionary *)getURLParameters
{
    
    // 查找参数
    NSRange range = [self rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 截取参数
    NSString *parametersString = [self substringFromIndex:range.location + 1];
    
    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}


#pragma mark - 设置字体的大小／颜色
+ (NSAttributedString *)setTitle:(NSString *)title titleColor:(UIColor *)titleColor titleFont:(UIFont *)titleFont value:(NSString *)value valueColor:(UIColor *)valueColor valueFont:(UIFont *)valueFont
{
    NSString *unionString = [NSString stringWithFormat:@"%@%@", title, value];
    
    NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:unionString];
    
    [str addAttribute:NSForegroundColorAttributeName value:titleColor range:NSMakeRange(0,title.length)];
    [str addAttribute:NSForegroundColorAttributeName value:valueColor range:NSMakeRange(title.length, value.length)];
    
    [str addAttribute:NSFontAttributeName value:titleFont range:NSMakeRange(0,title.length)];
    [str addAttribute:NSFontAttributeName value:valueFont range:NSMakeRange(title.length, value.length)];
    
    return [str copy];
}



+ (NSAttributedString *)setTitle:(NSString *)title titleColor:(UIColor *)titleColor value:(NSString *)value valueColor:(UIColor *)valueColor
{
    NSString *unionString = [NSString stringWithFormat:@"%@ %@", title, value];
    
    NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:unionString];
    
    [str addAttribute:NSForegroundColorAttributeName value:titleColor range:NSMakeRange(0,title.length)];
    [str addAttribute:NSForegroundColorAttributeName value:valueColor range:NSMakeRange(title.length+1, value.length)];
    
    return [str copy];
}

@end
